package com.ftp.utils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.util.ResourceBundle;

/**
 * 用于连接FTP服务器的类
 */
public class FtpConnectUtils {

    //ftp服务器的ip
    private static String ip;
    //ftp服务器的端口号默认为21
    private static Integer port;
    //ftp登录账号
    private static String username;
    //ftp登录密码
    private static String password;


    static {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("ftpconfig");
        ip = resourceBundle.getString("ftp.ip");
        port = Integer.valueOf(resourceBundle.getString("ftp.port"));
        username = resourceBundle.getString("ftp.username");
        password = resourceBundle.getString("ftp.password");
    }


    public static FTPClient connectFtpServer() {
        //ftp客户端，用于连接ftp服务器的
        FTPClient ftpClient = new FTPClient();
        //设置ftp字符集
        ftpClient.setControlEncoding("utf-8");
        //设置连接超时时间
        ftpClient.setConnectTimeout(1000 * 30);
        //设置被动模式，文件传输端口设置
        ftpClient.enterLocalPassiveMode();

        try {

            //连接ftp服务器
            ftpClient.connect(ip, port);
            //登录ftp服务器
            ftpClient.login(username, password);
            //设置文件传输模式为二进制，可以保证传输的内容不会被改变
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //是否成功登录服务器 [200,300) 表示成功
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                //打印登录失败的信息
                System.out.println("connect failed...ftp服务器:" + ip + ":" + port);
                //断开连接
                ftpClient.disconnect();
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("connect failed ----->" + e.getMessage());
            return null;
        }

        //打印登录成功的信息
        System.out.println("connect successful...ftp服务器:" + ip + ":" + port);
        return ftpClient;
    }


    /**
     * 关闭ftp服务器和流管道
     *
     * @param ftpClient
     */
    public static void closeFtpServer(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {//服务器还连着
            try {
                //断开连接
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
